﻿
/**
 * 数据同步事件管理器，可以定义，订阅相关事件
 * 
 * @export
 * @class DataSyncEventListener
 */
export class DataSyncEventListener {
    static Current: DataSyncEventListener = new DataSyncEventListener();
    constructor() { }
    private handerList: IEventHandler[] = [];

    /**
     * 注册数据和数据同步相关事件
     * @param  {IEventHandler} eventHandler 事件处理句柄
     */
    RegistEvent(eventHandler: IEventHandler) {
        this.handerList.push(eventHandler);
    }
    RemoveEvent(eventHandler: IEventHandler) {
        for (var i = 0; i < this.handerList.length; i++) {
            if (this.handerList[i].toString() == eventHandler.toString()) {
                this.handerList.splice(i, 1);
            }
        }
    }
    /**
     * On数据同步添加数据事件
     * @param  {} sender 触发者
     * @param  {} args 参数
     */
    OnAddDataSyncEvent(sender, args) {
        this.OnEvent(sender, args, "DataSyncAddEventHandler");
    }

    OnUpdateEvent(sender, args) {
        this.OnEvent(sender, args, "DataSyncUpdateEventHandler");
    }

    OnDeleteEvent(sender, args) {
        this.OnEvent(sender, args, "DataSyncDeleteEventHandler");
    }

    private OnEvent(sender, args, handlerName) {
        for (var h of this.handerList) {
            if (h.toString() == handlerName) {
                h.Handle(sender, args);
            }
        }
    }
}

interface IEventHandler {
    toString();
    Handle(sender, args): void;
}

export class DataSyncAddEventHandler implements IEventHandler {
    Handle(sender, args): void { };
    constructor(handle: (sender, args) => void) {
        this.Handle = handle;
    }
    toString() { return "DataSyncAddEventHandler"; };
}

export class DataSyncUpdateEventHandler implements IEventHandler {
    Handle(sender, args): void { };
    constructor(handle: (sender, args: { newItem: any }) => void) {
        this.Handle = handle;
    }
    toString() { return "DataSyncUpdateEventHandler"; };
}

export class DataSyncDeleteEventHandler implements IEventHandler {
    Handle(sender, args): void { };
    constructor(handle: (sender, args: { id: number | string, tableName: string }) => void) {
        this.Handle = handle;
    }
    toString() { return "DataSyncDeleteEventHandler"; };
}